import { getCompanyID, getInvoiceCode, getLevelZero, getPosIDs, getTenantID, getUserDepID, getUserID, requestFunComponFiex } from '@/utils';
import { useRequest } from 'umi';
import { generateRandomNumber } from '../common/Format';
import { useMemo } from 'react';
import { ApplyManageTab, sourceManageTab } from '../mconfig';
import { ILoadMapTypeAll } from '@/common';
import { getBaseUrl } from '@/services/urlconst';
const baseUrl = getBaseUrl();
/** 组件评标委员会 */
export const ExpertManageService = () => {
  const request = useRequest(
    (requestParams?: Record<string, any>) => {
      let params: any = {
        createCompanyID: getLevelZero(),
        current: 1,
        pageSize: 10,
        ...requestParams,
      };
      const reqUrl = `${baseUrl}/expertInfoController/dataGrid/createCompanyID`;

      delete params['applyFormNameDept'];
      delete params['applyFormNameUser'];
      if (params['createrID']?.length) {
        params['createrID'] = params['createrID']?.toString();
      } else {
        delete params['createrID'];
      }
      return requestFunComponFiex('POST', reqUrl, params);
    },
    {
      manual: false,
      paginated: true,
      defaultPageSize: 10,
    },
  );

  const data = useMemo(() => {
    if (request.data?.rows) {
      request.data?.rows?.forEach((item) => {
        // 给一个新值，然后删除id，在新增的时候不需要，只要expertID字段
        item.expertID = item?.id;
        item.mockID = generateRandomNumber('experts_');
        item.expertFlag = 0;
        delete item?.['id'];
      });
      return request.data?.rows;
    } else {
      return [];
    }
  }, [request.data?.rows]);

  return {
    expertRun: request.run,
    expertDataSource: data,
    expertLoading: request.loading,
    expertTableProps: request.tableProps,
  };
};

/** 请求抽取专家列表信息 */
export const getExtractExpertsDataGrid = (Callback: (res: Record<string, any>) => void) => {
  const request = useRequest(
    (payload) => {
      let bodyParams = {
        ...payload,
      };

      let reqUrl = `${baseUrl}/expertInfoController/randExpert`;
      return requestFunComponFiex('POST', reqUrl, bodyParams);
    },
    {
      manual: true,
      onSuccess: Callback,
    },
  );

  return {
    extractExpertsRun: request?.run,
    extractExpertsLoading: request?.loading,
    extractExpertsData: request?.data?.obj,
  };
};

/** 查询实施列表 */
export const getSourceListService = (curRes) => {
  const request = useRequest(
    (payload: Record<string, any>) => {
      let reqParams: Record<string, any> = {
        current: 1,
        pageSize: 10,
        sort: 'createTime',
        order: 'desc',
        state: `${getTenantID()}${ILoadMapTypeAll?.CURRYOUT_STATE}1004`, //澄清中
        ...sourceManageTab(curRes),
        ...payload,
      };
      let reqUrl = `${baseUrl}/purchaseSourceController/dataGrid/${reqParams?.params}`;
      return requestFunComponFiex('POST', reqUrl, reqParams);
    },
    {
      manual: true,
      paginated: true,
      defaultPageSize: 10,
    },
  );
  const requestManage = (reqParams) => {
    request.run({
      current: 1,
      pageSize: 10,
      ...reqParams,
    });
  };
  return {
    getSourceListRun: request.run,
    getSourceListLoading: request.loading,
    getSourceListPagination: request.pagination,
    requestManage,
  };
};

/** 暂存评标委员会 */
export const addExpertsSerivice = (Callback: (res) => void) => {
  const request = useRequest(
    (payload: any) => {
      let params = {
        ...payload,
        createrID: getUserID(),
        createPositionID: getPosIDs(),
        createDepartmentID: getUserDepID(),
        createCompanyID: getCompanyID(),
        state: `${getTenantID()}${ILoadMapTypeAll?.EXPERT_BUSINESSTYPE}1000`,
        // expertCode: `HLZB00KCPB${moment().format('YYMM')}`,
        expertCode: getInvoiceCode('PB'),
      };

      let reqUrl = `${baseUrl}/purchaseSourceExpertController/addRepresentative`;

      return requestFunComponFiex('POST', reqUrl, params);
    },
    {
      manual: true,
      onSuccess: Callback,
    },
  );
  return {
    addExpertsRun: request?.run,
    addExpertsLoading: request?.loading,
  };
};

/** 编辑评标委员会 */
export const editExpertsSerivice = (Callback: (res) => void) => {
  const request = useRequest(
    (payload: any) => {
      let params = {
        ...payload,
        modifyerID: getUserID(),
        modifyPositionID: getPosIDs(),
        modifyDepartmentID: getUserDepID(),
        modifyCompanyID: getCompanyID(),
        // createrID: getUserID(),
        // createPositionID: getPosIDs(),
        // createDepartmentID: getUserDepID(),
        // createCompanyID: getCompanyID(),
        // state: `${getTenantID()}${ILoadMapTypeAll?.EXPERT_BUSINESSTYPE}1000`,
      };

      let reqUrl = `${baseUrl}/purchaseSourceExpertController/editRepresentative`;

      return requestFunComponFiex('PUT', reqUrl, params);
    },
    {
      manual: true,
      onSuccess: Callback,
    },
  );
  return {
    editExpertsRun: request.run,
    editExpertsLoading: request.loading,
  };
};

/** 评标委员会详情 */
export const getExpertsSerivice = (Callback: (res) => void) => {
  const request = useRequest(
    (payload: any) => {
      // /purchaseSourceExpertController/getSourceExpertById
      let reqUrl = `${baseUrl}/purchaseSourceExpertController/getSourceExpertById/${payload?.id}/${getUserID()}`;
      return requestFunComponFiex('GET', reqUrl);
    },
    {
      manual: true,
      onSuccess: Callback,
    },
  );
  return {
    getExpertsRun: request.run,
    getExpertsLoading: request.loading,
    getExpertsReload: request?.refresh,
  };
};

export const ApplyManageService = (curRes, state = {}) => {
  /***获取数据字典**/
  const loadMdicIds: string[] = [`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}`];

  /**管理页列表接口 */
  const getApplyManageService = (pageSize: number = 10) => {
    const request: any = useRequest(
      (requestParams?: Record<string, any>) => {
        let params: any = {
          current: 1,
          pageSize: pageSize,
          dicTypeIds: loadMdicIds?.toString(),
          sort: 'createTime',
          order: 'desc',
          ...requestParams,
          ...ApplyManageTab(curRes),
          ...state,
        };

        const reqUrl = `${baseUrl}/purchaseApplyController/dataGrid/${params?.params}`;

        return requestFunComponFiex('POST', reqUrl, params);
      },

      {
        manual: false,
        paginated: true,
        defaultPageSize: pageSize,
      },
    );

    return {
      applyManageRun: request.run,
      applyManageDataSource: request.data?.rows || [],
      applyManageLoading: request.loading,
      applyManageTableProps: request.tableProps,
    };
  };

  return {
    getApplyManageService,
  };
};

/**
 * 查看当前流程进度
 * @controller 业务controller
 * @returns
 */
export const getImageByProcInstIDService = (callBack: (res: any) => void) => {
  const getImageByProcInstID = useRequest(
    (params: any) => {
      let personUrl = `${baseUrl}/purchaseSourceExpertController/getImageByProcInstID/${params?.procInstID}`;
      return requestFunComponFiex('GET', personUrl, {});
    },
    {
      manual: true,
      onSuccess: callBack,
    },
  );

  const data = useMemo(() => {
    return getImageByProcInstID?.data;
  }, [getImageByProcInstID?.data]);

  return {
    getImageByProcInstIDRun: getImageByProcInstID?.run,
    getImageByProcInstIDLoading: getImageByProcInstID?.loading,
    getImageByProcInstIDData: data,
  };
};

/**同步PDF*/
export const syncPDFtoOAServices = (cb: (res: Record<string, any>) => void) => {
  const request = useRequest(
    (payload) => {
      let reqParams = { ...payload };
      let reqUrl = `${baseUrl}/purchaseSourceExpertController/syncWorkFlow`;
      return requestFunComponFiex('POST', reqUrl, reqParams);
    },
    {
      manual: true,
      onSuccess: cb,
    },
  );

  return {
    syncPDFtoOARun: request?.run,
    syncPDFtoOALoading: request?.loading,
  };
};
